#include "stdafx.h"
#include "OnOffButton.h"

#include "2DUtils.h"
#include "Text.h"

using namespace mgui;

OnOffButton::OnOffButton( const Rect & bounds, const std::string & text, bool exclusiveWhenEnabled )
	: Text(text), Enabled(false), ExclusiveWhenEnabled(exclusiveWhenEnabled), mIsExclusive(false), mDragging(false)
{
	setBounds(bounds);
}

void OnOffButton::drawSelf()
{
	XMVECTOR color = Enabled ? XMVectorSet(0.5f, 0.3f, 0.5f, 0.0f) : XMVectorSet(0.1f, 0.1f, 0.1f, 0.0f);
	mgfx::Utils2D::drawRect(mBounds.X, mBounds.Y, mBounds.Width, mBounds.Height, color);
	mgfx::Text2D::draw(Text, mBounds.X, mBounds.Y);
}

bool OnOffButton::processLButtonUpInside( const Point & pt )
{
	if(mDragging)
	{
		mDragging = false;
	}
	else
	{
		Enabled = !Enabled;

		OnOffEventArgs args(Enabled);
		callListeners(EVENT_STATE_CHANGED, args);

		if(ExclusiveWhenEnabled)
		{
			if(Enabled)
				mIsExclusive = mRootControl->setExclusiveInputReceiver(*this);
			else
			{
				mRootControl->unsetExclusiveInputReceiver(*this);
				mIsExclusive = false;
			}
		}
	}

	return true;
}

bool OnOffButton::processLButtonUpOutside( const Point & pt )
{
	if(mIsExclusive)
	{
		mDragging = false;
		return true;
	}

	return false;
}

bool OnOffButton::processLButtonDownInside( const Point & pt )
{
	// dont start dragging if click started inside button, otherwise impossible to turn the button off (every click initiates drag)
	return true;
}

bool OnOffButton::processLButtonDownOutside( const Point & pt )
{
	if(mIsExclusive)
	{
		mDragging = true;
		mPrevMousePos = pt;
		return true;
	}

	return false;
}

bool OnOffButton::processMouseMovedInside( const Point & pt )
{
	return processMouseMoved(pt);
}

bool OnOffButton::processMouseMovedOutside( const Point & pt )
{
	return processMouseMoved(pt);
}

bool OnOffButton::processMouseMoved( const Point & pt )
{
	if(mDragging)
	{
		MouseDragEventArgs args(mPrevMousePos, pt);
		callListeners(EVENT_MOUSE_DRAGGED, args);

		mPrevMousePos = pt;

		return true;
	}

	return false;
}
